const input=document.getElementById('input')
const send=document.getElementById('send')
const infobox=document.getElementById('infobox')
const inter=document.getElementById('inter')
const username=document.getElementById('username')
const color=['#45C195','#C5517D','#C4904E','#B5CD69','#4E91C4','#B364CB','#C8B35D','#3AADAA','#8A40BE','#C24C8B']
const upButton=document.getElementById('upButton')


// 用户名称与字体颜色
let name
let textColor


// 类型
const TYPE_ENTER=0
const TYPE_MSG=1
const TYPE_CLOSE=2

// socket
let socket

inter.addEventListener('click',()=>{
    // 01 设置用户名
    if(username.value===''){
        document.getElementById('message').innerHTML='请输入用户名！'
        return
    }
    name=username.value
    document.getElementById('userHeader').innerHTML='用户：'+name

    // 02 为用户设置颜色
    textColor=color[Math.floor(Math.random()*10)]

    // 03 切换显示
    const firstStep=document.getElementById('firstStep')
    const secondStep=document.getElementById('secondStep')
    firstStep.style.display='none'
    secondStep.style.display='block'

    // 04 进入聊天室
    socket = new WebSocket('ws://localhost:8001');
    socket.addEventListener('open', function (event) {
        let userInfo={
            username:name,
            type:TYPE_ENTER,
        }
        socket.send(JSON.stringify(userInfo));
    });

    // 05 接受信息
    socket.addEventListener('message', function (event) {
        const data=JSON.parse(event.data)

        let div = document.createElement('div');
        div.innerHTML = data.msg

        if(data.type===TYPE_ENTER||data.type===TYPE_CLOSE){
            div.style.color = 'rgb(151 151 151)'
        }else{
            div.style.color = data.color
        }

        let span=document.createElement('span')
        span.innerHTML='-----'+new Date().toLocaleTimeString()
        div.appendChild(span)

        document.getElementById('infobox').appendChild(div)
        infobox.scrollTop=infobox.scrollHeight-infobox.offsetHeight  //保存视图在底部
    });

    // 06 发送信息
    send.addEventListener('click',()=>{
        sendMessage()
    })
    document.addEventListener('keyup',(e)=>{
        if (e.code === 'Enter') {
            sendMessage()
        }
    })

    upButton.addEventListener('click',()=>{
        infobox.scrollTop=0
    })
})


function sendMessage(){
    const message2=document.getElementById('message2')
    if(input.value===''){
        message2.innerHTML='消息不能为空'
        return
    }
    message2.innerHTML=''
    
    let userInfo={
        type:TYPE_MSG,
        color:textColor,
        msg:input.value
    }
    socket.send(JSON.stringify(userInfo))
    input.value=''
}